package com.example.train_operate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.train_operate.dto.LoginDTO;
import com.example.train_operate.dto.UserDTO;
import com.example.train_operate.entity.User;
import com.example.train_operate.service.OnlineUserService;
import com.example.train_operate.service.UserService;
import com.example.train_operate.mapper.UserMapper;
import com.example.train_operate.util.*;
import com.example.train_operate.ws.model.OnlineUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.train_operate.util.ReidsConstants.LOGIN_CODE_KEY;
import static com.example.train_operate.util.ReidsConstants.LOGIN_CODE_TTL;

/**
* @author 21609
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-08-07 18:48:13
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private OnlineUserService onlineUserService;

    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    public Result login(LoginDTO loginDTO) {
        String userName = loginDTO.getUserName();
        String password = loginDTO.getPassword();
        if (RegexUtils.isUserInvalid(userName)) {
            return Result.fail().message("用户账号格式错误");
        } else if (RegexUtils.isPasswordInvalid(password)) {
            return Result.fail().message("用户密码格式错误");
        } else {
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_name", userName);
            queryWrapper.eq("is_delete", 0);
            User user = (User)this.userMapper.selectOne(queryWrapper);
            if (user == null) {
                return Result.fail().message("账号不存在");
            } else {
                String password1 = user.getPassword();
                if (!CommunityUtil.verifyPassword(password, password1)) {
                    return Result.fail().message("密码错误");
                } else {
                    String token = JwtUtil.createToken(user.getId());
                    log.info("token======>{}", token);
                    user.setToken(token);
                    UserDTO userDTO = (UserDTO) BeanUtil.copyProperties(user, UserDTO.class, new String[0]);
                    userDTO.setDeviceType(loginDTO.getDeviceType());
                    log.info("userDTO=============>{}" + String.valueOf(userDTO));
                    Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, true, true);
                    Map<String, String> stringMap = new HashMap();
                    Iterator var11 = userMap.entrySet().iterator();
                    while(var11.hasNext()) {
                        Map.Entry<String, Object> entry = (Map.Entry)var11.next();
                        stringMap.put((String)entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : null);
                    }
                    String key = LOGIN_CODE_KEY + token;
                    this.stringRedisTemplate.opsForHash().putAll(key, stringMap);
                    this.stringRedisTemplate.expire(key, LOGIN_CODE_TTL, TimeUnit.HOURS);
                    return Result.ok(userDTO).message("登录成功");
                }
            }
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Result register(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        user.setDisplayName(user.getUserName());
        if(RegexUtils.isUserInvalid(userName)){
            return Result.fail().message("账号格式错误");
        }
        if(RegexUtils.isPasswordInvalid(password)){
            return Result.fail().message("密码格式错误");
        }
        String md5Password = CommunityUtil.encryptWithSalt(password,CommunityUtil.generateSalt());
        user.setPassword(md5Password);
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", userName);
        queryWrapper.eq("is_delete", 0);
        User user1 = userMapper.selectOne(queryWrapper);
        if(user1 != null){
            return Result.fail().message("账号已存在");
        }
        userMapper.insert(user);
        return Result.ok().message("注册成功");
    }

    /**
     * 获取用户列表
     * @return
     */
    @Override
    public Result getUserList() {
        UserDTO userDTO = UserHolder.getUser();
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", 0)
                .ne("id", userDTO.getId());
        List<User> userList = userMapper.selectList(queryWrapper);
        if(userList == null){
            return Result.ok().message("未查询到用户信息");
        }
        return Result.ok(userList);
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public Result logout() {
        UserDTO user = UserHolder.getUser();
        String token = user.getToken();
        if(token.isEmpty()){
            return Result.fail().message("用户未登录");
        }
        String key = LOGIN_CODE_KEY + token;
        stringRedisTemplate.delete(key);
        return Result.ok();
    }

    /**
     * 获取所有在线用户
     * @return
     */
    @Override
    public Result getAllOnlineUsers(String excludeUserId) {
        try{
            List<OnlineUser> onlineUsers = onlineUserService.getAllOnlineUsers();
            //排除当前用户
            if(excludeUserId != null){
                onlineUsers = onlineUsers.stream()
                        .filter(user -> !user.getUserId().equals(excludeUserId))
                        .collect(Collectors.toList());
            }
            List<Map<String, Object>> userList = onlineUsers.stream()
                    .map(user -> {
                        Map<String, Object> userData = new HashMap<>();
                        userData.put("userId", user.getUserId());
                        userData.put("username", user.getUserName());
                        userData.put("displayName", user.getDisplayName());
                        userData.put("deviceType", user.getDeviceType());
                        userData.put("callStatus", user.getCallStatus());
                        return userData;
                    })
                    .collect(Collectors.toList());
            return Result.ok(Map.of("users", userList));
        } catch (Exception e){
            return Result.fail().message("获取在线用户失败");
        }
    }

    /**
     * 获取所有Android设备
     * @return
     */
    @Override
    public Result getAndroidDevices(String excludeUserId) {
        try{
            List<OnlineUser> androidUsers = onlineUserService.getOnlineUserByDeviceType("ANDROID");
            // 排除当前用户
            if (excludeUserId != null){
                androidUsers = androidUsers.stream()
                        .filter(user -> !user.getUserId().equals(excludeUserId))
                        .collect(Collectors.toList());
            }
            // 创建设备列表
            List<Map<String, Object>> deviceList = androidUsers.stream()
                    .map(user -> {
                        Map<String, Object> deviceData = new HashMap<>();
                        deviceData.put("userId", user.getUserId());
                        deviceData.put("username", user.getUserName());
                        deviceData.put("displayName", user.getDisplayName());
                        deviceData.put("callStatus", user.getCallStatus());
                        return deviceData;
                    })
                    .collect(Collectors.toList());
            return Result.ok(deviceList);
        } catch (Exception e){
            return Result.fail().message("获取Android设备列表失败");
        }
    }

    /**
     * 获取在线用户统计
     * @return
     */
    @Override
    public Result getStats() {
        try{
            int totalOnline = onlineUserService.getOnlineUserCount();
            int webUsers = onlineUserService.getOnlineUserByDeviceType("WEB").size();
            int androidUsers = onlineUserService.getOnlineUserByDeviceType("ANDROID").size();
            Map<String, Object> stats = new HashMap<>();
            stats.put("total", totalOnline);
            stats.put("web", webUsers);
            stats.put("android", androidUsers);
            return Result.ok(stats);
        } catch (Exception e){
            return Result.fail().message("获取在线用户统计失败");
        }
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Override
    public Result deleteUser(Integer userId) {
        try{
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", userId)
                    .eq("is_delete", 0);
            User user = userMapper.selectOne(queryWrapper);
            if(user == null){
                return Result.fail().message("用户不存在！");
            }
            user.setIsDelete(1);
            userMapper.updateById(user);
            return Result.ok().message("用户删除成功");
        }catch (Exception e){
            return Result.fail().message("用户删除失败！");
        }
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Override
    public Result updateUser(User user) {
        try{
            userMapper.updateById(user);
            return Result.ok().message("用户信息更新成功");
        }catch (Exception e){
            return Result.fail().message("用户信息更新失败");
        }
    }

    /**
     * 更新密码
     * @param user
     * @return
     */
    @Override
    public Result updatePassword(User user) {
        try{
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", user.getId())
                    .eq("is_delete", 0);
            User user1 = userMapper.selectOne(queryWrapper);
            if(user1 == null){
                return Result.fail().message("用户不存在！");
            }
            String password = user.getPassword();
            String newPassword = CommunityUtil.encryptWithSalt(password, CommunityUtil.generateSalt());
            user1.setPassword(newPassword);
            userMapper.updateById(user1);
            return Result.ok().message("密码更新成功");
        } catch (Exception e){
            return Result.fail().message("密码更新失败！");
        }
    }


}




